package com.cjst.controller.sys;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.cjst.controller.base.BaseController;
import com.cjst.pojo.sys.SysMenu;
import com.cjst.pojo.sys.VersionUpdate;
import com.cjst.sdp.util.MapUtils;
import com.cjst.service.sys.VersionUpdateService;
import com.cjst.sql.C;
import com.cjst.sql.Method;
import com.cjst.sql.WherePrams;
import com.cjst.util.CloneClass;
import com.cjst.util.Md5Util;
import com.cjst.util.code.PageUtil;
import com.cjst.util.common.DateUtil;
import com.cjst.util.json.ResultObj;

@Controller
@RequestMapping(value="/sys/apk_version")
public class ApkVersionController  extends BaseController {
	
	@Value("${img.location}")
    private String fileUploadPath;
	
	 @Value("${file.path}")
	 private String filePath;
	
	@Autowired
	private VersionUpdateService versionUpdateService;
	
	public String test() {
		return null;
	}
	
	@RequestMapping(value="")
	public String index() {
		
		return "/system/apk_version/apk_version";
	}
	
	@ResponseBody
	@RequestMapping(value="/list")
	public Object list() {
		WherePrams wherePrams=Method.where("isDelete", C.EQ, 0);
		
		PageUtil<VersionUpdate> pageUtil = versionUpdateService.listPageCount(wherePrams);
        List<VersionUpdate> VersionUpdates = pageUtil.getData();
        
        List<Map<String, Object>> maps = new ArrayList<>();
        for(VersionUpdate tmp:VersionUpdates) {
        	Map<String, Object> VersionMap = MapUtils.transBean2Map(tmp);
        	 maps.add(VersionMap);
        }
        PageUtil<Map<String, Object>> pages = new PageUtil<>();

        CloneClass.getClone(pageUtil, pages);
        pages.setData(maps);
		
		return this.packForBT(pages);
	}
			
	@RequestMapping(value="/add")
	public String add() {
		return "/system/apk_version/add";
	}
	
	@ResponseBody
	@RequestMapping(value="/save/add", method = RequestMethod.POST)
	public Object save(VersionUpdate versionUpdate)  throws Exception {
		
		//目前仅仅针对单一app包
		WherePrams wherePrams=Method.where("isDelete", C.EQ, 0);
		wherePrams.orderBy(" version_code desc limit 0,1");
		List<VersionUpdate> versionUpdates=versionUpdateService.list(wherePrams);
		
		int current_version_code=0;
		
		if(versionUpdates==null||versionUpdates.size()==0) {
			//this is newest one;
		}
		current_version_code=versionUpdates.get(0).getVersionCode();
		
		versionUpdate.setVersionCode(current_version_code+1);
		String createTime = DateUtil
                .dateFormatToString(DateUtil.getCurrentDate(), "yyyy-MM-dd HH:mm:ss");
		versionUpdate.setCreate_time(createTime);
		String result=versionUpdateService.addLocalByid(versionUpdate);
		
		
		return  new ResultObj(0, "成功", result);
	}
	
	public String delete() {
		return null;
	}
	
	 /**
     * 上传头像
     * @param request
     * @param file
     * @return
     */
    @RequestMapping("/upload")
    @ResponseBody
    @Transactional
    public Object upload(HttpServletRequest request, MultipartFile file,String dirs) {
        try {

            //文件上传路径
            String serverPath = fileUploadPath;


            //文件名称
            String fileName = file.getOriginalFilename();
            //文件后缀
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            
            if(!"apk".equals(suffix)) {
                return new ResultObj(0, "错误的文件", null);
            }
            
            String uploadDir = "/"  + "apk";
            

            //检查目录是否存在
            File dir = new File(serverPath + uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            //随机名称
            String randomFileName = UUID.randomUUID().toString();
            //文件存在服务器上的路径
            String fileUrl = uploadDir + "/" + randomFileName + "." + suffix;

            //将文件上传到文集的物理地址
            File serverFile = new File(serverPath + fileUrl);
            file.transferTo(serverFile);
            log.info("文件上传成功");
            
            
            
            
            //耗时未知
            long beginTime = System.currentTimeMillis();
            String md5=Md5Util.getMD5(serverFile);
            long endTime = System.currentTimeMillis();
            log.info("MD5:" + md5 + "\t 耗时:" + ((endTime - beginTime) / 1000) + "s");
            
            HashMap<String, String> map=new HashMap<String, String>();
            map.put("fileUrl", filePath + fileUrl);
            map.put("size", String.valueOf(serverFile.length()));
            map.put("md5",md5);
            
            
            return new ResultObj(1, "文件上传成功", map);

        } catch (Exception e) {
            log.error(e.getMessage());
            return new ResultObj(0, e.getMessage(), null);
        }

    }

}
